const mongoose = require('mongoose')
const Router = require('koa-router')
const ArticleSchema = mongoose.model('Article')
const ArticleRouter = new Router()
ArticleRouter.get('/get', async (ctx) => {
  try {
    const { currPage } = ctx.request.query
    const skipCount = (currPage - 1) * 10
    const res = await ArticleSchema.find({}, 'subTitle nickName avatarUrl createTime, commentCount').sort({createTime: -1}).limit(10).skip(skipCount).exec()
    ctx.body = {
      code: 200,
      message: res
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})
ArticleRouter.post('/add', async (ctx) => {
  try {
    const newArticleSchema = new ArticleSchema(ctx.request.body)
    await newArticleSchema.save()
    ctx.body = {
      code: 200,
      message: '新增成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})
ArticleRouter.get('/detail', async (ctx) => {
  try {
    const { articleId } = ctx.request.query
    const res = await ArticleSchema.findById(articleId).exec()
    ctx.body = {
      code: 200,
      message: res
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

module.exports = ArticleRouter
